package com.flydog.mall.service.impl.ums;

import com.flydog.mall.dto.RegisterUserInfoParam;
import com.flydog.mall.entity.ums.UmsUserInfo;
import com.flydog.mall.repository.ums.UmsUserInfoRepository;
import com.flydog.mall.security.JwtTokenUtil;
import com.flydog.mall.service.ums.UmsUserAdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Cao
 * @description 用户管理
 * @create 2021-04-11
 */
@Service
public class UmsUserAdminImpl implements UmsUserAdminService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UmsUserInfoRepository userInfoRepository;

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Override
    public String login(String userName, String password) {
        String token = null;
        Optional<UmsUserInfo> userInfoOption = userInfoRepository.findByUserName(userName);
        if(userInfoOption.isPresent()){
            UmsUserInfo userInfo = userInfoOption.get();
            if(passwordEncoder.matches(password, userInfo.getPassword())){
                return tokenUtil.generateToken(userName);
            }
        }
        return null;
    }

    @Override
    public int register(RegisterUserInfoParam userInfoParam) {
        UmsUserInfo userInfo = new UmsUserInfo();
        BeanUtils.copyProperties(userInfoParam, userInfo);
        String passWordEncoded = passwordEncoder.encode(userInfoParam.getPassword());
        userInfo.setPassword(passWordEncoded);
        userInfoRepository.save(userInfo);
        return 1;
    }
}
